﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;


namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class DatabaseCheckStateOffline : IssueTypeCheckBase
    {

        public DatabaseCheckStateOffline()
        {
            IssueTypeId = 3004;
        }

        public override void Check()
        {
            try
            {
                // Database check status is Offline
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);


                // Query for an offline database status 
                var qry = from d in dc.Databases

                          where d.State != "ONLINE"
                          && d.SourceDatabaseId == null

                          select d;

                foreach (var database in qry)
                {
                    IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                    //Create new Issue

                    Issue issue = new Issue();
                    issue.IssueType = issueType;
                    issue.TargetId = database.DatabaseID;
                    issue.Description = issueType.Description.Replace("{Database}", database.DatabaseName);

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

        }

    }
}
